// Copyright 2012 Google Inc. All Rights Reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// This code is loaded after the HTML tree is declared in popup.html

// access data & methods from background.js
var brain = chrome.extension.getBackgroundPage().brain;

// The args to be passed to generatePSL() API
var selectedPubID;
var selectedAdvID;
var pslName;
var productURL;

var relArray;  // available list of relationships
var dropDown;

// Fetches the current tab where the popup is showing, passes to buildUI.
chrome.tabs.getSelected(null, buildUI);

// a braindead hack until we normalize our advertiser domain data
function getMinimalDomain(domain) {
  var parts = domain.split('.');
  if (parts[0] === 'www') {
    parts.shift();
    return parts.join('.');
  } else {
    return domain;
  }
}

function buildUI(currentTab) {
  productURL = currentTab.url;
  var currentDomain = brain.getDomain(currentTab.url);
  console.log('Currently visiting domain: ' + currentDomain);

  var relDiv = document.getElementById('relationshipDiv');
  brain.deleteChildren(relDiv);

  // look up current domain in domainMap literally
  relArray = brain.domainMap[currentDomain];
  if (! relArray) {
    // fallback hack: try looking up current domain without 'www'
    relArray = brain.domainMap[getMinimalDomain(currentDomain)];
  }

  if (! relArray) {
    // don't show adv info area
    var info = document.getElementById('advInfo');
    info.parentNode.removeChild(info);
    var logo = document.getElementById('advLogo');
    logo.parentNode.removeChild(logo);
    var dl = document.getElementById('dl');
    dl.parentNode.removeChild(dl);

    // build 'sorry' div
    var advBody = document.getElementById('advBody');
    var newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'note');
    advBody.appendChild(newDiv);
    newDiv.appendChild(document.createTextNode
                       ('Sorry!  Either this site does not belong to a ' +
                        'GAN advertiser, or you have no relationship ' +
                        'with this advertiser.'));
    console.log('Sorry, no relationship with this advertiser.');

  } else {

    var refreshLink = document.createElement('a');
    refreshLink.innerHTML = '(refresh relationships)';
    refreshLink.href = './options.html';

    // 99% of all cases:  a single relationship
    if (relArray.length == 1) {
      selectedPubID = relArray[0].pubID;
      selectedAdvID = relArray[0].advID;
      var pubName = brain.publishers[selectedPubID].name;
      var advName = brain.advertisers[selectedAdvID].name;

      var text = 'Working as publisher "' + pubName +
                 '" as an affiliate of "' + advName + '".    ';
      relDiv.appendChild(document.createTextNode(text));
      console.log(text);
      relDiv.appendChild(refreshLink);

      showAdvInfo();

    } else {
      // build dropdown of possible relationships
      console.log('Multiple relationships available:');
      relDiv.appendChild(document.createTextNode
                         ('Please choose a relationship to use:    '));
      relDiv.appendChild(refreshLink);

      dropDown = document.createElement('select');
      dropDown.setAttribute('id', 'dropDown');
      dropDown.addEventListener('change', onDropDownChange);
      var l = relArray.length;
      for (var i = 0; i < l; i++) {
        var pubID = relArray[i].pubID;
        var advID = relArray[i].advID;
        var pubName = brain.publishers[pubID].name;
        var advName = brain.advertisers[advID].name;
        var choice = document.createElement('option');
        var text = pubName + ' as an affiliate of ' + advName;
        choice.appendChild(document.createTextNode(text));
        dropDown.appendChild(choice);
      }
      relDiv.appendChild(document.createElement('p'));
      relDiv.appendChild(dropDown);

      onDropDownChange();  // sets globally selected pub and adv
      showAdvInfo();
    }
  }
}


// utility:  shows advertiser info in top of popup
function showAdvInfo() {
  var pslButton = document.getElementById('pslButton');
  pslButton.addEventListener('click', onPSLClick);
  var adv = brain.advertisers[selectedAdvID];
  document.getElementById('advLogo').src = adv.logoUrl;
  document.getElementById('advName').appendChild(
      document.createTextNode(adv.name));
  var advProfileURL =
    'http://www.google.com/affiliatenetwork/c.html?repType=links#p' +
    selectedPubID + ':advertisers!advId=' + selectedAdvID;
  document.getElementById('advLink').href = advProfileURL;
  if (! adv.allowPublisherCreatedLinks) {
    var newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'note');
    var advBody = document.getElementById('advBody');
    advBody.appendChild(newDiv);
    newDiv.appendChild(document.createTextNode
                    ('Sorry! You have a relationship with this advertiser, ' +
                     'but they do not allow publishers to build links.'));
    pslButton.disabled = true;
  }
}


function onDropDownChange() {
  var i = document.getElementById('dropDown').selectedIndex;
  console.log('Current value of dropdown is: ' + i);
  selectedPubID = relArray[i].pubID;
  selectedAdvID = relArray[i].advID;
}


function onPSLClick() {
  console.log('Generating PSL...');

  if (! selectedPubID) {
    alert('Please choose a publisher.');
    return;
  } else if (! selectedAdvID) {
      alert('Please choose an advertiser.');
      return;
  }

  // show spinning timer gif
  var waitImg = document.createElement('img');
  waitImg.setAttribute('src', 'loading.gif');
  waitImg.setAttribute('id', 'waitImg');
  var waitPara = document.createElement('p');
  waitPara.setAttribute('id', 'waitPara');
  waitPara.appendChild(waitImg);
  var dl = document.getElementById('dl');
  dl.appendChild(waitPara);

  pslName = document.getElementById('pslNameField').value;
  if (! pslName)
    pslName = 'PSL from GAN Link Builder';
  brain.generatePSL(selectedPubID, selectedAdvID, pslName,
                    productURL, pslCallback);
}


function pslCallback(link) {
  // append the PSL to UI
  var textarea = document.getElementById('deep_link');
  brain.deleteChildren(textarea);
  textarea.appendChild(document.createTextNode(link));

  // replace spinning gif with instructions.
  var waitPara = document.getElementById('waitPara');
  waitPara.removeChild(document.getElementById('waitImg'));
  waitPara.appendChild(document.createTextNode(
      'Copy this link to your clipboard; it may take 15 minutes to be active.'));
}


